//
//  CaptureDetailViewController.m
//  CarPark
//
//  Created by oceans on 2019/8/8.
//  Copyright © 2019 oceans. All rights reserved.
//

#import "CaptureDetailViewController.h"
#import "ReviewDetailCollectionViewCell.h"
#import "CaptureLocationViewController.h"
#import "CaptureInstallListCollectionViewCell.h"
#import <UIImageView+WebCache.h>
//#import <SDWebImage/UIImageView+WebCache.h>

@interface CaptureDetailViewController () <UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, CaptureDeleteDelegate>

@property (strong, nonatomic) UICollectionView *collection;
@property (strong, nonatomic) NSDictionary *info;
@property (strong, nonatomic) NSMutableArray *array;
@end

@implementation CaptureDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"任务详情";
    self.array = [NSMutableArray array];
    [self loadData];
}

- (void)loadData {
    
    defweakself
    [HttpRequest getURL:ktask_detail paras:@{@"type": @"task_capture_install", @"id": [NSString stringWithFormat:@"%d", __id]} showProgress:NO successful:^(id  _Nullable result) {
        
        NSLog(@"%@", result);
        weakself.info = result[@"datas"];
        [weakself setupView];
    } failed:^(int code, NSString * _Nullable errMsg) {
        
    }];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self requestData];
}

- (void)requestData {
    
    defweakself
    [HttpRequest getURL:kcapture_list paras:@{@"task_id": [NSString stringWithFormat:@"%d", __id]} showProgress:NO successful:^(id  _Nullable result) {
        NSLog(@"%@", result);
        [weakself.array removeAllObjects];
        [weakself.array addObjectsFromArray:result[@"datas"]];
        [weakself.collection reloadData];
    } failed:^(int code, NSString * _Nullable errMsg) {
        
    }];
}

- (void)setupView {
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    self.collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, XNavigationHeight, ScreenWidth, ScreenHeight-XNavigationHeight-XBotSafeSpace-40.0) collectionViewLayout:layout];
    _collection.delegate = self;
    _collection.dataSource = self;
    _collection.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_collection];
    [_collection registerNib:[UINib nibWithNibName:@"ReviewDetailCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"ReviewDetailCollectionViewCell"];
    [_collection registerNib:[UINib nibWithNibName:@"CaptureInstallListCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"CaptureInstallListCollectionViewCell"];
    
    // 完成 30，中 10， 审 20，
    if ([_info[@"status"] intValue] != 20 && [_info[@"status"] intValue] != 30) {
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.titleLabel.font = [UIFont systemFontOfSize:15.0];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [button setTitle:@"电话联系" forState:UIControlStateNormal];
        button.frame = CGRectMake(0, ScreenHeight-XBotSafeSpace-40.0, ScreenWidth*0.3, 40.0+XBotSafeSpace);
        [button addTarget:self action:@selector(call) forControlEvents:UIControlEventTouchUpInside];
        button.backgroundColor = COLOR(102, 102, 102, 1);
        [self.view addSubview:button];
        
        UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
        button1.titleLabel.font = [UIFont systemFontOfSize:15.0];
        [button1 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [button1 setTitle:@"安装完成" forState:UIControlStateNormal];
        button1.frame = CGRectMake(ScreenWidth*0.3, ScreenHeight-XBotSafeSpace-40.0, ScreenWidth*0.25, 40.0+XBotSafeSpace);
        [button1 addTarget:self action:@selector(finish) forControlEvents:UIControlEventTouchUpInside];
        button1.backgroundColor = COLOR(252, 13, 27, 1);
        [self.view addSubview:button1];
        
        UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom];
        button2.titleLabel.font = [UIFont systemFontOfSize:15.0];
        [button2 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [button2 setTitle:@"立即安装" forState:UIControlStateNormal];
        button2.frame = CGRectMake(ScreenWidth*0.3+ScreenWidth*0.25, ScreenHeight-XBotSafeSpace-40.0, ScreenWidth*0.45, 40.0+XBotSafeSpace);
        [button2 addTarget:self action:@selector(install) forControlEvents:UIControlEventTouchUpInside];
        button2.backgroundColor = COLOR(56, 152, 24, 1);
        [self.view addSubview:button2];
    }
}

- (void)finish {
    
    defweakself
    [HttpRequest postURL:kfinish_capture paras:@{@"id": [NSString stringWithFormat:@"%@", _info[@"id"]]} showProgress:YES successful:^(id  _Nullable result) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakself.navigationController popToRootViewControllerAnimated:YES];
        });
    } failed:^(int code, NSString * _Nullable errMsg) {
        
    }];
}

- (void)install {
    
    CaptureLocationViewController *con = [[CaptureLocationViewController alloc] init];
    con.info = _info;
    con.captures = _array;
    [self.navigationController pushViewController:con animated:YES];
}

- (void)call {
    
    defweakself
    UIAlertController *con = [UIAlertController alertControllerWithTitle:@"电话" message:_info[@"contact_tel"] preferredStyle:UIAlertControllerStyleAlert];
    [con addAction:[UIAlertAction actionWithTitle:@"返回" style:UIAlertActionStyleCancel handler:nil]];
    [con addAction:[UIAlertAction actionWithTitle:@"立即呼叫" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSString *tel = weakself.info[@"parking"][@"contact_tel"];
        tel = [@"telprompt://" stringByAppendingString:tel];
        if (@available(iOS 10.0, *)) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:tel] options:@{} completionHandler:nil];
        }else {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:tel]];
        }
    }]];
    [self presentViewController:con animated:YES completion:nil];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    return 2;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    
    return 0.0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    
    return 0.0;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        return CGSizeMake(ScreenWidth, 40.0);
    }
    return CGSizeMake(ScreenWidth, 100.0);
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    if (section == 0) {
        return 6+2;
    }
    return _array.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 1) {
        
        NSDictionary *dic = _array[indexPath.item];
        CaptureInstallListCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CaptureInstallListCollectionViewCell" forIndexPath:indexPath];
        [cell.imageView sd_setImageWithURL:[NSURL URLWithString:dic[@"thumb"]]];
        cell.label1.text = dic[@"name"];
        cell.label2.text = [NSString stringWithFormat:@"状态：%@", dic[@"status_label"]];
        cell.label3.text = [NSString stringWithFormat:@"位置：%@", dic[@"parking_position"]];
        cell.tag = indexPath.item;
        cell.delegate = self;
        return cell;
    }
    ReviewDetailCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ReviewDetailCollectionViewCell" forIndexPath:indexPath];
    if (indexPath.item == 0) {
        cell.leftLabel.text = @"开始时间";
        cell.rightLabel.text = _info[@"created_at"];
    }else if (indexPath.item == 1) {
        cell.leftLabel.text = @"结束时间";
        cell.rightLabel.text = _info[@"etc_time"];
    }else if (indexPath.item == 0+2) {
        cell.leftLabel.text = @"停车场名称";
        cell.rightLabel.text = _info[@"parking"][@"name"];
    }else if (indexPath.item == 1+2) {
        cell.leftLabel.text = @"详细地址";
        cell.rightLabel.text = _info[@"parking"][@"address"];
    }else if (indexPath.item == 2+2) {
        cell.leftLabel.text = @"经销商";
        cell.rightLabel.text = _info[@"dealer"][@"name"];
    }else if (indexPath.item == 3+2) {
        cell.leftLabel.text = @"联系人";
        cell.rightLabel.text = _info[@"parking"][@"contact_person"];
    }else if (indexPath.item == 4+2) {
        cell.leftLabel.text = @"联系电话";
        cell.rightLabel.text = _info[@"parking"][@"contact_tel"];
    }else if (indexPath.item == 5+2) {
        cell.leftLabel.text = @"所在地区";
        cell.rightLabel.text = (_info[@"parking"][@"addr_full_name"] != [NSNull null] ? _info[@"parking"][@"addr_full_name"] : @"");
    }
    return cell;
}

- (void)deleteCapture:(NSInteger)tag {
    
    defweakself
    UIAlertController *con = [UIAlertController alertControllerWithTitle:@"删除设备" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [con addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [con addAction:[UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [HttpRequest postURL:kcapture_delete paras:@{@"id": [NSString stringWithFormat:@"%@", weakself.array[tag][@"id"]]} showProgress:YES successful:^(id  _Nullable result) {
            [weakself.array removeObjectAtIndex:tag];
            [weakself.collection deleteItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:tag inSection:1]]];
        } failed:^(int code, NSString * _Nullable errMsg) {
            
        }];
    }]];
    [self presentViewController:con animated:YES completion:nil];
}

@end
